<template>
  <div class="quality-reports">
    <div class="page-header">
      <div class="header-left">
        <h2>质量报告</h2>
        <p>质量检测数据统计分析和报告生成</p>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="generateReport">
          <el-icon><Document /></el-icon>
          生成报告
        </el-button>
        <el-button type="success" @click="exportReport">
          <el-icon><Download /></el-icon>
          导出报告
        </el-button>
      </div>
    </div>

    <div class="page-content">
      <!-- 时间筛选 -->
      <div class="filter-section">
        <el-form :model="filterForm" inline>
          <el-form-item label="时间范围">
            <el-date-picker
              v-model="filterForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 300px"
              @change="handleDateChange"
            />
          </el-form-item>
          <el-form-item label="商品分类">
            <el-select
              v-model="filterForm.category"
              placeholder="请选择商品分类"
              clearable
              style="width: 200px"
              @change="handleCategoryChange"
            >
              <el-option label="全部" value="" />
              <el-option label="生鲜果蔬" value="fresh" />
              <el-option label="食品饮料" value="food" />
              <el-option label="日用品" value="daily" />
            </el-select>
          </el-form-item>
          <el-form-item label="供应商">
            <el-select
              v-model="filterForm.supplier"
              placeholder="请选择供应商"
              clearable
              style="width: 200px"
              @change="handleSupplierChange"
            >
              <el-option label="全部" value="" />
              <el-option
                v-for="supplier in suppliers"
                :key="supplier.id"
                :label="supplier.name"
                :value="supplier.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="refreshData">
              <el-icon><Refresh /></el-icon>
              刷新数据
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 统计概览 -->
      <div class="overview-section">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-card class="overview-card">
              <div class="overview-content">
                <div class="overview-icon total">
                  <el-icon><Document /></el-icon>
                </div>
                <div class="overview-info">
                  <div class="overview-value">{{ overview.totalInspections }}</div>
                  <div class="overview-label">总检测数</div>
                  <div class="overview-trend">
                    <span :class="overview.totalTrend >= 0 ? 'up' : 'down'">
                      {{ Math.abs(overview.totalTrend) }}%
                    </span>
                    较上期
                  </div>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="overview-card">
              <div class="overview-content">
                <div class="overview-icon passed">
                  <el-icon><Check /></el-icon>
                </div>
                <div class="overview-info">
                  <div class="overview-value">{{ overview.passedInspections }}</div>
                  <div class="overview-label">合格检测</div>
                  <div class="overview-trend">
                    <span :class="overview.passedTrend >= 0 ? 'up' : 'down'">
                      {{ Math.abs(overview.passedTrend) }}%
                    </span>
                    较上期
                  </div>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="overview-card">
              <div class="overview-content">
                <div class="overview-icon failed">
                  <el-icon><Close /></el-icon>
                </div>
                <div class="overview-info">
                  <div class="overview-value">{{ overview.failedInspections }}</div>
                  <div class="overview-label">不合格检测</div>
                  <div class="overview-trend">
                    <span :class="overview.failedTrend <= 0 ? 'up' : 'down'">
                      {{ Math.abs(overview.failedTrend) }}%
                    </span>
                    较上期
                  </div>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="overview-card">
              <div class="overview-content">
                <div class="overview-icon rate">
                  <el-icon><TrendCharts /></el-icon>
                </div>
                <div class="overview-info">
                  <div class="overview-value">{{ overview.passRate }}%</div>
                  <div class="overview-label">合格率</div>
                  <div class="overview-trend">
                    <span :class="overview.rateTrend >= 0 ? 'up' : 'down'">
                      {{ Math.abs(overview.rateTrend) }}%
                    </span>
                    较上期
                  </div>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 图表分析 -->
      <div class="charts-section">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-card class="chart-card">
              <template #header>
                <div class="card-header">
                  <span>合格率趋势</span>
                </div>
              </template>
              <div class="chart-container">
                <div ref="passRateChart" style="width: 100%; height: 300px;"></div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card class="chart-card">
              <template #header>
                <div class="card-header">
                  <span>检测类型分布</span>
                </div>
              </template>
              <div class="chart-container">
                <div ref="inspectionTypeChart" style="width: 100%; height: 300px;"></div>
              </div>
            </el-card>
          </el-col>
        </el-row>
        
        <el-row :gutter="20" style="margin-top: 20px;">
          <el-col :span="12">
            <el-card class="chart-card">
              <template #header>
                <div class="card-header">
                  <span>商品分类质量对比</span>
                </div>
              </template>
              <div class="chart-container">
                <div ref="categoryChart" style="width: 100%; height: 300px;"></div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card class="chart-card">
              <template #header>
                <div class="card-header">
                  <span>供应商质量排名</span>
                </div>
              </template>
              <div class="chart-container">
                <div ref="supplierChart" style="width: 100%; height: 300px;"></div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 质量问题分析 -->
      <el-card class="analysis-card">
        <template #header>
          <div class="card-header">
            <span>质量问题分析</span>
          </div>
        </template>
        
        <el-tabs v-model="activeTab" type="border-card">
          <el-tab-pane label="常见问题" name="common">
            <div class="problem-analysis">
              <el-table :data="commonProblems" style="width: 100%" border>
                <el-table-column prop="problem" label="问题类型" min-width="150" />
                <el-table-column prop="count" label="出现次数" width="100" />
                <el-table-column prop="percentage" label="占比" width="100">
                  <template #default="{ row }">
                    {{ row.percentage }}%
                  </template>
                </el-table-column>
                <el-table-column prop="products" label="涉及商品" min-width="200" />
                <el-table-column prop="suggestion" label="改进建议" min-width="200" />
                <el-table-column label="趋势" width="100">
                  <template #default="{ row }">
                    <el-tag :type="row.trend === 'up' ? 'danger' : 'success'">
                      {{ row.trend === 'up' ? '上升' : '下降' }}
                    </el-tag>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-tab-pane>
          
          <el-tab-pane label="检测项目分析" name="items">
            <div class="item-analysis">
              <el-table :data="testItemAnalysis" style="width: 100%" border>
                <el-table-column prop="testItem" label="检测项目" width="150" />
                <el-table-column prop="totalTests" label="检测次数" width="100" />
                <el-table-column prop="passedTests" label="合格次数" width="100" />
                <el-table-column prop="failedTests" label="不合格次数" width="100" />
                <el-table-column prop="passRate" label="合格率" width="100">
                  <template #default="{ row }">
                    <el-progress
                      :percentage="row.passRate"
                      :color="getPassRateColor(row.passRate)"
                      :stroke-width="8"
                    />
                  </template>
                </el-table-column>
                <el-table-column prop="mainIssue" label="主要问题" min-width="200" />
              </el-table>
            </div>
          </el-tab-pane>
          
          <el-tab-pane label="改进建议" name="suggestions">
            <div class="suggestions">
              <el-timeline>
                <el-timeline-item
                  v-for="(suggestion, index) in improvementSuggestions"
                  :key="index"
                  :timestamp="suggestion.date"
                  :type="suggestion.priority"
                >
                  <div class="suggestion-content">
                    <h4>{{ suggestion.title }}</h4>
                    <p>{{ suggestion.description }}</p>
                    <div class="suggestion-details">
                      <el-tag v-for="tag in suggestion.tags" :key="tag" size="small">
                        {{ tag }}
                      </el-tag>
                    </div>
                  </div>
                </el-timeline-item>
              </el-timeline>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>
  </div>
</template>

<script>
import { defineComponent, ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { Document, Download, Refresh, Check, Close, TrendCharts } from '@element-plus/icons-vue'
import * as echarts from 'echarts'

export default defineComponent({
  name: 'QualityReports',
  components: {
    Document,
    Download,
    Refresh,
    Check,
    Close,
    TrendCharts
  },
  setup() {
    const activeTab = ref('common')
    
    // 筛选表单
    const filterForm = reactive({
      dateRange: [],
      category: '',
      supplier: ''
    })
    
    // 统计概览
    const overview = reactive({
      totalInspections: 1250,
      passedInspections: 1180,
      failedInspections: 70,
      passRate: 94.4,
      totalTrend: 12.5,
      passedTrend: 15.2,
      failedTrend: -8.3,
      rateTrend: 2.1
    })
    
    // 模拟供应商数据
    const suppliers = ref([
      { id: 1, name: '绿色农场供应商' },
      { id: 2, name: '优质食品供应商' },
      { id: 3, name: '新鲜果蔬供应商' }
    ])
    
    // 常见问题数据
    const commonProblems = ref([
      {
        problem: '农药残留超标',
        count: 25,
        percentage: 35.7,
        products: '有机苹果、有机白菜',
        suggestion: '加强种植环节管理，减少农药使用',
        trend: 'down'
      },
      {
        problem: '包装破损',
        count: 18,
        percentage: 25.7,
        products: '有机胡萝卜、有机土豆',
        suggestion: '改进包装材料，加强运输管理',
        trend: 'down'
      },
      {
        problem: '外观不合格',
        count: 15,
        percentage: 21.4,
        products: '有机苹果、有机白菜',
        suggestion: '加强分级筛选，提高外观标准',
        trend: 'up'
      },
      {
        problem: '微生物超标',
        count: 12,
        percentage: 17.2,
        products: '有机白菜',
        suggestion: '加强清洗消毒，控制存储条件',
        trend: 'down'
      }
    ])
    
    // 检测项目分析
    const testItemAnalysis = ref([
      {
        testItem: '农药残留',
        totalTests: 1250,
        passedTests: 1225,
        failedTests: 25,
        passRate: 98.0,
        mainIssue: '个别批次农药残留超标'
      },
      {
        testItem: '重金属',
        totalTests: 1250,
        passedTests: 1240,
        failedTests: 10,
        passRate: 99.2,
        mainIssue: '铅含量偶尔超标'
      },
      {
        testItem: '微生物',
        totalTests: 1250,
        passedTests: 1238,
        failedTests: 12,
        passRate: 99.0,
        mainIssue: '大肠菌群偶尔超标'
      },
      {
        testItem: '外观检查',
        totalTests: 1250,
        passedTests: 1235,
        failedTests: 15,
        passRate: 98.8,
        mainIssue: '包装破损、外观不完整'
      },
      {
        testItem: '理化指标',
        totalTests: 1250,
        passedTests: 1245,
        failedTests: 5,
        passRate: 99.6,
        mainIssue: '水分含量偶尔超标'
      }
    ])
    
    // 改进建议
    const improvementSuggestions = ref([
      {
        date: '2024-01-15',
        title: '加强供应商质量管理',
        description: '建立供应商质量评价体系，定期进行质量培训，提高供应商质量意识。',
        priority: 'primary',
        tags: ['供应商管理', '质量培训']
      },
      {
        date: '2024-01-14',
        title: '优化检测流程',
        description: '完善检测标准，优化检测流程，提高检测效率和准确性。',
        priority: 'success',
        tags: ['流程优化', '标准完善']
      },
      {
        date: '2024-01-13',
        title: '改进包装设计',
        description: '针对包装破损问题，改进包装材料选择和设计，提高包装强度。',
        priority: 'warning',
        tags: ['包装改进', '材料优化']
      },
      {
        date: '2024-01-12',
        title: '加强存储管理',
        description: '完善存储条件控制，建立温湿度监控系统，确保商品存储质量。',
        priority: 'info',
        tags: ['存储管理', '环境控制']
      }
    ])
    
    // 图表引用
    const passRateChart = ref(null)
    const inspectionTypeChart = ref(null)
    const categoryChart = ref(null)
    const supplierChart = ref(null)
    
    // 时间范围变化
    const handleDateChange = () => {
      refreshData()
    }
    
    // 商品分类变化
    const handleCategoryChange = () => {
      refreshData()
    }
    
    // 供应商变化
    const handleSupplierChange = () => {
      refreshData()
    }
    
    // 刷新数据
    const refreshData = () => {
      ElMessage.success('数据已刷新')
      // 这里应该重新加载数据和更新图表
      updateCharts()
    }
    
    // 生成报告
    const generateReport = () => {
      ElMessage.success('质量报告生成成功')
      // 这里实现报告生成逻辑
    }
    
    // 导出报告
    const exportReport = () => {
      ElMessage.success('质量报告导出成功')
      // 这里实现报告导出逻辑
    }
    
    // 获取合格率颜色
    const getPassRateColor = (passRate) => {
      if (passRate >= 95) return '#67C23A'
      if (passRate >= 85) return '#E6A23C'
      return '#F56C6C'
    }
    
    // 初始化图表
    const initCharts = () => {
      nextTick(() => {
        // 合格率趋势图
        const passRateChartInstance = echarts.init(passRateChart.value)
        const passRateOption = {
          title: {
            text: '合格率趋势',
            left: 'center'
          },
          tooltip: {
            trigger: 'axis'
          },
          xAxis: {
            type: 'category',
            data: ['1月', '2月', '3月', '4月', '5月', '6月']
          },
          yAxis: {
            type: 'value',
            min: 80,
            max: 100
          },
          series: [{
            data: [92, 93, 94, 95, 94.4, 95.2],
            type: 'line',
            smooth: true,
            lineStyle: {
              color: '#67C23A'
            },
            areaStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [{
                  offset: 0, color: 'rgba(103, 194, 58, 0.3)'
                }, {
                  offset: 1, color: 'rgba(103, 194, 58, 0.1)'
                }]
              }
            }
          }]
        }
        passRateChartInstance.setOption(passRateOption)
        
        // 检测类型分布图
        const inspectionTypeChartInstance = echarts.init(inspectionTypeChart.value)
        const inspectionTypeOption = {
          title: {
            text: '检测类型分布',
            left: 'center'
          },
          tooltip: {
            trigger: 'item'
          },
          series: [{
            type: 'pie',
            radius: '50%',
            data: [
              { value: 800, name: '常规检测' },
              { value: 300, name: '专项检测' },
              { value: 100, name: '复检' },
              { value: 50, name: '抽检' }
            ],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }]
        }
        inspectionTypeChartInstance.setOption(inspectionTypeOption)
        
        // 商品分类质量对比图
        const categoryChartInstance = echarts.init(categoryChart.value)
        const categoryOption = {
          title: {
            text: '商品分类质量对比',
            left: 'center'
          },
          tooltip: {
            trigger: 'axis'
          },
          xAxis: {
            type: 'category',
            data: ['生鲜果蔬', '食品饮料', '日用品']
          },
          yAxis: {
            type: 'value',
            min: 80,
            max: 100
          },
          series: [{
            data: [94.4, 96.2, 98.5],
            type: 'bar',
            itemStyle: {
              color: function(params) {
                const colors = ['#67C23A', '#409EFF', '#E6A23C']
                return colors[params.dataIndex]
              }
            }
          }]
        }
        categoryChartInstance.setOption(categoryOption)
        
        // 供应商质量排名图
        const supplierChartInstance = echarts.init(supplierChart.value)
        const supplierOption = {
          title: {
            text: '供应商质量排名',
            left: 'center'
          },
          tooltip: {
            trigger: 'axis'
          },
          xAxis: {
            type: 'value',
            min: 80,
            max: 100
          },
          yAxis: {
            type: 'category',
            data: ['供应商C', '供应商B', '供应商A']
          },
          series: [{
            data: [98.5, 95.2, 92.8],
            type: 'bar',
            itemStyle: {
              color: '#409EFF'
            }
          }]
        }
        supplierChartInstance.setOption(supplierOption)
      })
    }
    
    // 更新图表
    const updateCharts = () => {
      // 这里更新图表数据
    }
    
    onMounted(() => {
      initCharts()
    })
    
    return {
      activeTab,
      filterForm,
      overview,
      suppliers,
      commonProblems,
      testItemAnalysis,
      improvementSuggestions,
      passRateChart,
      inspectionTypeChart,
      categoryChart,
      supplierChart,
      handleDateChange,
      handleCategoryChange,
      handleSupplierChange,
      refreshData,
      generateReport,
      exportReport,
      getPassRateColor
    }
  }
})
</script>

<style scoped>
.quality-reports {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header-left h2 {
  margin: 0 0 5px 0;
  color: #2563eb;
}

.header-left p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.page-content {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.filter-section {
  margin-bottom: 20px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.overview-section {
  margin-bottom: 20px;
}

.overview-card {
  border: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.overview-content {
  display: flex;
  align-items: center;
  padding: 10px;
}

.overview-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  font-size: 24px;
  color: white;
}

.overview-icon.total {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.overview-icon.passed {
  background: linear-gradient(135deg, #67C23A 0%, #85ce61 100%);
}

.overview-icon.failed {
  background: linear-gradient(135deg, #F56C6C 0%, #f78989 100%);
}

.overview-icon.rate {
  background: linear-gradient(135deg, #E6A23C 0%, #ebb563 100%);
}

.overview-info {
  flex: 1;
}

.overview-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.overview-label {
  font-size: 14px;
  color: #909399;
  margin-bottom: 5px;
}

.overview-trend {
  font-size: 12px;
  color: #909399;
}

.overview-trend .up {
  color: #67C23A;
}

.overview-trend .down {
  color: #F56C6C;
}

.charts-section {
  margin-bottom: 20px;
}

.chart-card {
  margin-bottom: 20px;
}

.chart-container {
  padding: 10px 0;
}

.analysis-card {
  margin-bottom: 20px;
}

.card-header {
  font-weight: bold;
  color: #2563eb;
}

.problem-analysis,
.item-analysis {
  padding: 20px 0;
}

.suggestions {
  padding: 20px 0;
}

.suggestion-content h4 {
  margin: 0 0 10px 0;
  color: #2563eb;
}

:is(.suggestion-content p) {
  margin: 0 0 10px 0;
  color: #666;
}

.suggestion-details {
  display: flex;
  gap: 5px;
  flex-wrap: wrap;
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }
  
  .header-right {
    width: 100%;
    display: flex;
    gap: 10px;
  }
  
  .filter-section {
    padding: 15px;
  }
  
  .overview-content {
    flex-direction: column;
    text-align: center;
  }
  
  .overview-icon {
    margin-right: 0;
    margin-bottom: 10px;
  }
}
</style> 